package com.michale.framework.security.service.impl;

import com.michale.common.domain.permissions.RoleEntity;
import com.michale.common.domain.permissions.UserEntity;
import com.michale.common.utils.security.SecurityUtils;
import com.michale.framework.security.service.PermissionService;
import com.michale.system.service.MenuService;
import com.michale.system.service.RoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Michale
 * @apiNote 授权信息封装
 */
@Service("permissionService")
public class PermissionServiceImpl implements PermissionService {
    @Resource
    private RoleService roleService;

    @Resource
    private MenuService menuService;

    /**
     * 获取角色数据权限
     *
     * @param userEntity 用户信息
     * @return 角色数据权限 ("admin 或者 common ...")
     */
    @Override
    public Set<String> getRolePermission(UserEntity userEntity) {
        Set<String> roles = new HashSet<>();

        /*如果是管理员则拥有所有权限*/
        if (SecurityUtils.isAdmin(userEntity.getIdentity())) {
            roles.add("admin");
        } else {
            //查询普通用户的权限信息
            Set<String> permission = roleService.selectPermissionByUserId(userEntity.getUserId());
            roles.addAll(permission);
        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     *
     * @param userEntity 用户信息
     * @return 菜单数据权限 ("*.*.* 或者 system:user:list ...")
     */
    public Set<String> getMenuPermission(UserEntity userEntity) {
        //封装菜单数据权限权限信息
        Set<String> menuPermission = new HashSet<>();
        // 管理员拥有所有权限
        if (SecurityUtils.isAdmin(userEntity.getIdentity())) {
            menuPermission.add("*:*:*");
        } else {
            List<RoleEntity> roles = userEntity.getRoleEntityList();
            /*用户有多个角色*/
            if (!roles.isEmpty() &&roles.size() > 1) {
                for (RoleEntity roleEntity : roles) {
                    Set<String> roleMenuPerms = menuService.selectMenuPermsByRoleId(roleEntity.getRoleId());
                    roleEntity.setPermissions(roleMenuPerms);
                    menuPermission.addAll(roleMenuPerms);
                }
            } else {
                /*用户只有一个角色*/
                Set<String> roleMenuPerms = menuService.selectMenuPermsByUserId(userEntity.getUserId());
                menuPermission.addAll(roleMenuPerms);
            }
        }
        return menuPermission;
    }
}
